package com.sk.leetcode.arithmetic.test11_20;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class Test14 {
    public static void main(String[] args) {
        String[] strs = {"aa","a"};
        String s = longestCommonPrefix(strs);
        System.out.println(s);
    }

    public static String longestCommonPrefix(String[] strs) {
        if(strs.length == 0){
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        int index = 0;
        while (true) {
            String s = "";
            for (int i = 0; i < strs.length; i++) {
                if(i == 0) {
                    if(strs[i].length() > index) {
                        s = strs[i].substring(index, index + 1);
                    } else {
                        return stringBuilder.toString();
                    }
                } else {
                    if(strs[i].length() > index) {
                        if(!s.equals(strs[i].substring(index, index + 1))) {
                            return stringBuilder.toString();
                        }
                    } else {
                        return stringBuilder.toString();
                    }
                }
                if(i == strs.length - 1) {
                    stringBuilder.append(s);
                    index++;
                }
            }
        }
    }

}
